package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.robot.admin.client.GoodsClient;
import com.robot.admin.pojo.client.Goods;
import com.robot.admin.pojo.client.GoodsCategory;
import com.robot.admin.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;
import util.UpdateUtil;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 商品模块
 *
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * goods表的on_sale 上下架状态 0-下架 1-上架
     */
    private String goodsOnSaleFailed = "0";
    private String goodsOnSaleSuccess = "1";
    /**
     * goods表status 审核状态  0-待审核 1-审核通过 2-审核未通过
     */
    private String goodsStatus = "0";
    private String goodsStatusSuccess = "1";
    private String goodsStatusFailed = "2";


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "findGoodsBySearch/{page}/{size}", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Result findGoodsBySearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(goodsClient.thirdFindGoodsBySearch(searchMap, page, size)));
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "findGoodsById/{id}", method = RequestMethod.GET)
    public Result findGoodsById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Goods goodsInDb = JSON.parseObject(goodsClient.thirdFindGoodsById(id), Goods.class);
        logger.info("goodsInDb=" + goodsInDb);
        String message = checkPojo(goodsInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        return new Result(StatusCode.SUCCESS_QUERY, goodsInDb);
    }

    /**
     * 编辑商品
     *
     * @param goods
     */
    @RequestMapping(value = "updateGoods/{id}", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Result updateGoods(@RequestBody Goods goods, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Goods goodsInDb = JSON.parseObject(goodsClient.thirdFindGoodsById(id), Goods.class);
        logger.info("goodsInDb=" + goodsInDb);
        String message = checkPojo(goodsInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        goods.setStoreId(goodsInDb.getStoreId());
        if (goods.getCategoryId() != null && !"".equals(goods.getCategoryId()) && JSON.parseObject(goodsClient.thirdFindGoodsCategoryById(goods.getCategoryId()), GoodsCategory.class) == null) {
            return new Result(StatusCode.ERROR_GOODS_CATEGORY_DOES_NOTE_EXIST);
        }
        if (goods.getPrice() != null && !"".equals(goods.getPrice()) && goods.getPrice().compareTo(BigDecimal.ZERO) == -1) {
            return new Result(StatusCode.ERROR_GOODS_PRICE_INVALID);
        }
        if (goods.getStock() != null && !"".equals(goods.getStock()) && goods.getStock() < 0) {
            return new Result(StatusCode.ERROR_GOODS_STOCK_INVALID);
        }
        if (goods.getImages() != null && !"".equals(goods.getImages())) {
            Map<String, Object> map = checkUtil.checkImages(goods.getImages());
            Boolean flag = (Boolean) map.get("flag");
            if (!flag) {
                return new Result(StatusCode.ERROR_FILE_FORMAT, (String) map.get("message"));
            } else {
                goods.setImages((String) map.get("message"));
            }
        }

        goods.setCreatedAt(goodsInDb.getCreatedAt());
        UpdateUtil.copyNonNullProperties(goods, goodsInDb);
        goodsInDb.setId(id);
        goodsInDb.setStatus("0");
        goodsInDb.setUpdatedAt(LocalDateTime.now());
        goodsClient.thirdUpdateGoodsByGoods(JSON.toJSONString(goodsInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 审核商品 审核状态  0-待审核 1-审核通过 2-审核未通过
     *
     * @param goods
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Result trialGoods(@RequestBody Goods goods, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId() + ", goods's id=" + id);
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Goods goodsInDb = JSON.parseObject(goodsClient.thirdFindGoodsById(id), Goods.class);
        logger.info("goodsInDb=" + goodsInDb);
        String message = checkPojo(goodsInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        String status = goods.getStatus();
        if (status == null || "".equals(status)) {
            return new Result(StatusCode.ERROR_GOODS_STATUS_REQUIRED);
        }
        if (goodsStatusSuccess.equals(status)) {
        } else if (goodsStatusFailed.equals(status)) {
            goodsInDb.setOnSale(goodsOnSaleFailed);
        } else {
            return new Result(StatusCode.ERROR_GOODS_STATUS_INVALID);
        }
        goodsInDb.setStatus(status);
        goodsInDb.setUpdatedAt(LocalDateTime.now());
        goodsClient.thirdUpdateGoodsByGoods(JSON.toJSONString(goodsInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 上下架商品 上下架状态 0-下架 1-上架
     *
     * @param id
     * @param onSale
     * @return
     */
    @RequestMapping(value = "onSaleGoods/{id}/{onSale}", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Result onSaleGoods(@PathVariable String id, @PathVariable String onSale) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Goods goodsInDb = JSON.parseObject(goodsClient.thirdFindGoodsById(id), Goods.class);
        logger.info("goodsInDb=" + goodsInDb);
        if (goodsInDb == null) {
            return new Result(StatusCode.ERROR_GOODS_DOES_NOTE_EXIST);
        }

        logger.info("onSale=" + onSale + ",and goodsInDb onSale=" + goodsInDb.getOnSale());
        if (goodsOnSaleFailed.equals(onSale) || goodsOnSaleSuccess.equals(onSale)) {
            if (goodsOnSaleSuccess.equals(onSale) && goodsOnSaleSuccess.equals(goodsInDb.getOnSale())) {
                return new Result(StatusCode.ERROR, "商品已经是上架状态了!");
            }
            if (goodsOnSaleFailed.equals(onSale) && goodsOnSaleFailed.equals(goodsInDb.getOnSale())) {
                return new Result(StatusCode.ERROR, "商品已经是下架状态了!");
            }
            if (goodsOnSaleSuccess.equals(onSale)) {
                goodsInDb.setStatus("0");
            }
            goodsInDb.setOnSale(onSale);
        } else {
            return new Result(StatusCode.ERROR_GOODS_ON_SALE_INVALID);
        }
        goodsClient.thirdUpdateGoodsByGoods(JSON.toJSONString(goodsInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "deleteGoods/{id}", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Result deleteGoodsById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Goods goodsInDb = JSON.parseObject(goodsClient.thirdFindGoodsById(id), Goods.class);
        String message = checkPojo(goodsInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        if (goodsOnSaleSuccess.equals(goodsInDb.getOnSale())) {
            return new Result(StatusCode.ERROR_GOODS_ON_SALE_INVALID_DELETE);
        }
        goodsInDb.setDeletedAt(LocalDateTime.now());
        goodsClient.thirdUpdateGoodsByGoods(JSON.toJSONString(goodsInDb));
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 检查实体类是否存在
     *
     * @param goodsInDb
     * @return
     */
    public String checkPojo(Goods goodsInDb) {
        if (goodsInDb == null) {
            return ("该商品不存在");
        }
        if (goodsInDb.getDeletedAt() != null) {
            return ("该商品已被删除");
        }
        return "";
    }
}
